"use server"
import {Table} from "@/components/table";
import {createClient} from "@/utils/supabase/server";
import CopyButton from "@/components/copy-button";

export type JetBrainsType = {
    availability: number,
    created_at: string,
    id: number,
    updated_at: string,
    url: string | null
}[];

function processJetBrainsData(data: JetBrainsType | null): [string, JetBrainsType | null] {
    if (!data || data.length === 0) {
        return ["", null];
    }

    // 过滤掉 null 的 updated_at 并转换为 Date
    const validDates = data
        .filter(item => item.created_at !== null)
        .map(item => new Date(item.created_at as string));

    // 找到最近的 updated_at
    const latestUpdatedTime = validDates.length > 0
        ? new Date(Math.max(...validDates.map(date => date.getTime() + 8 * 60 * 60 * 1000))).toISOString().replace('T', ' ').split('.')[0]
        : "";


    // 排序函数
    const sortedData = data.slice().sort((a, b) => {
        // 比较 availability
        if (a.availability !== b.availability) {
            return (b.availability || 0) - (a.availability || 0);
        }
        // 如果 availability 相同，比较 created_at
        return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
    });

    return [latestUpdatedTime, sortedData];
}


export default async function Home() {
  const supabase = createClient()
  const { data: jetbrains, error } = await supabase
      .from('jetbrains')
      .select('*')


    if(error) {
        return (
            <main className="flex min-h-screen flex-col items-center px-24 py-8">
                <div className="z-10 w-full max-w-5xl items-center font-serif">
                    <p className="fixed w-full px-8 left-0 top-0 flex text-2xl font-bold from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:p-4">
                        JetBrains 系列全家桶激活服务器 (每日更新)
                    </p>
                    <p className="fixed w-full px-8 left-0 top-0 flex text-md font-bold from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:p-4">
                        进度条为测试连接状态，并非一定可激活成功；如果某个URL无法激活，请切换下一个，总有可用的。
                    </p>
                </div>

                <div
                    className="pt-20 flex place-items-center">
                    资源请求失败，请稍后重新尝试。
                </div>
            </main>
        )
    }


    const [latestUpdatedTime, sortedData] = processJetBrainsData(jetbrains);


  return (
      <main className="flex min-h-screen flex-col items-center px-3 sm:px-6 md:px-12 lg:px-16 xl:px-24 py-8">
          <div className="z-10 w-full max-w-5xl items-center justify-between font-serif">
              <div className="w-full px-3 md:px-6 lg:px-8 left-0 top-0 font-bold from-zinc-200 pb-6 pt-8 backdrop-blur-2xl static">
                  <p className={'text-3xl'}>JetBrains 系列全家桶激活服务器 (每日更新)</p>
                  <p className="text-base pt-2">
                      进度条为测试连接状态，并非一定可激活成功；如果某个URL无法激活，请切换下一个，总有可用的。
                  </p>
              </div>

          </div>

          <div
              className="pt-8 place-items-center">
              <Table update_time={latestUpdatedTime} data={sortedData}/>
          </div>
      </main>
  )
}


















